import { ref } from 'vue'

export interface Notification {
  id: string
  type: 'success' | 'error' | 'warning' | 'info'
  title: string
  message?: string
  duration?: number
  closable?: boolean
}

// 全局通知列表
const notifications = ref<Notification[]>([])

// 生成唯一ID
let notificationId = 0
function generateId(): string {
  return `notification-${++notificationId}`
}

// 通知组合式函数
export function useNotification() {
  // 添加通知
  function addNotification(notification: Omit<Notification, 'id'>): string {
    const id = generateId()
    const newNotification: Notification = {
      id,
      duration: 5000,
      closable: true,
      ...notification
    }
    
    notifications.value.push(newNotification)
    
    // 自动移除
    if (newNotification.duration && newNotification.duration > 0) {
      setTimeout(() => {
        removeNotification(id)
      }, newNotification.duration)
    }
    
    return id
  }
  
  // 移除通知
  function removeNotification(id: string) {
    const index = notifications.value.findIndex(n => n.id === id)
    if (index !== -1) {
      notifications.value.splice(index, 1)
    }
  }
  
  // 清除所有通知
  function clearNotifications() {
    notifications.value = []
  }
  
  // 便捷方法
  function notify(title: string, message?: string, type: Notification['type'] = 'info') {
    return addNotification({ type, title, message })
  }
  
  function notifySuccess(title: string, message?: string) {
    return notify(title, message, 'success')
  }
  
  function notifyError(title: string, error?: any) {
    let message = ''
    if (error) {
      if (error instanceof Error) {
        message = error.message
      } else if (typeof error === 'string') {
        message = error
      } else if (error.message) {
        message = error.message
      } else {
        message = JSON.stringify(error)
      }
    }
    return notify(title, message, 'error')
  }
  
  function notifyWarning(title: string, message?: string) {
    return notify(title, message, 'warning')
  }
  
  function notifyInfo(title: string, message?: string) {
    return notify(title, message, 'info')
  }
  
  return {
    notifications,
    addNotification,
    removeNotification,
    clearNotifications,
    notify,
    notifySuccess,
    notifyError,
    notifyWarning,
    notifyInfo
  }
} 